package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

//删除图书操作
public class DeleteOperation implements IOperation {
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书！");
        //业务逻辑可以自己实现
        //删除图书就是要删除的元素，后面的元素依次向前覆盖
        System.out.println("请输入书名：");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();

        int pos = -1;
        int currentSize = bookList.getUsedSize();
        int i = 0;
        for (; i < currentSize; i++) {
            Book book = bookList.getBooks(i);
            if (book.getName().equals(name)) {
                pos = i;
                break;
            }
        }

        if (i == currentSize) {
            System.out.println("未找到要删除的图书！");
            return;
        }
        //开始删除
        //currentSize - 1 处理越界问题
        int j = pos;
        for (; j < currentSize - 1; j++) {
            bookList.setBooks(j, bookList.getBooks(j + 1));
        }
        bookList.setBooks(j, null);
        bookList.setUsedSize(currentSize - 1);
    }
}
